package com.leenleda.ips.activity.adapter;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.ImageView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.ViewDataBinding;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.leenleda.ips.R;
import com.leenleda.ips.databinding.ItemImageBinding;
import com.leenleda.ips.entity.MediaEntity;
import com.leenleda.ips.util.FileUtils;
import com.leenleda.ips.util.LogUtils;
import com.leenleda.ips.util.Utils;
import com.leenleda.ips.widget.banner.BannerAdapter;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * 自定义布局，图片
 */
public class ImageAdapter extends BannerAdapter<MediaEntity, ImageAdapter.ViewHolder> {

    private Context context;
    public ImageAdapter(Context context, List<MediaEntity> mDatas) {
        //设置数据，也可以调用banner提供的方法,或者自己在adapter中实现
        super(mDatas);
        this.context = context;
    }

    //更新数据
    public void updateData(List<MediaEntity> data) {
        //这里的代码自己发挥，比如如下的写法等等
        mDatas.clear();
        mDatas.addAll(data);
        notifyDataSetChanged();
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        ItemImageBinding binding = ItemImageBinding.bind(LayoutInflater.from(context).inflate(R.layout.item_image,parent,false));
        return new ViewHolder(binding);
    }

    @Override
    public ViewHolder onCreateHolder(ViewGroup parent, int viewType) {
        ItemImageBinding binding = ItemImageBinding.bind(LayoutInflater.from(context).inflate(R.layout.item_image,parent,false));
        return new ViewHolder(binding);
    }

    @Override
    public void onBindView(ViewHolder holder, MediaEntity data, int position, int size) {
        final ItemImageBinding binding=(ItemImageBinding) holder.getBinding();
        String path = "";
        String[] strs = data.getPath().split("/");
        try {
            path = data.getPath().replace(strs[strs.length - 1], "") + URLEncoder.encode(strs[strs.length - 1], "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
//        String pathFi = FileUtils.getPath(Constant.CACHE_FOLDER);
//        File file = new File(pathFi);
//        List<String> idList = new ArrayList<>();
//        if (file.isDirectory()){
//            for (File fi : file.listFiles()){
//                String name = fi.getName();
//                String[] aa = name.replace(".png", "").split("_");
//                if (aa.length > 1)
//                    idList.add(aa[aa.length - 1]);
//            }
//        }
//        Log.e("tag", "=====idList======" + data.getId() + ",=" + idList);
        String fiPNG = FileUtils.getVideoUrl(data, ".png");
        Log.e("tag", "=====fiPNG======" + fiPNG);
        if (!TextUtils.isEmpty(Utils.getStringValue(fiPNG))){
            String mSource = fiPNG;
            Log.e("tag", "=====mSource======" + mSource);
            loadImage(binding.scanImage, mSource);
            return;
        }

        String finalPath = path;
        LogUtils.e("DFSDFSDF", "==save=======path==" + path);
        Glide.with(context).downloadOnly().load(path)
                .listener(new RequestListener<File>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<File> target, boolean isFirstResource) {
                        LogUtils.e("DFSDFSDF", "====onLoadFailed======" + finalPath);
                        loadImage(binding.scanImage, finalPath);
                        return false;
                    }
                    @Override
                    public boolean onResourceReady(File resource, Object model, Target<File> target, DataSource dataSource, boolean isFirstResource) {
                        loadImage(binding.scanImage, resource.getAbsolutePath());
                        LogUtils.e("DFSDFSDF", "====onResourceReady======" + resource.getAbsolutePath());
//                        listener.save(resource, System.currentTimeMillis() + "_" + data.getId() + ".png");

                        FileUtils.copyFile(resource.getAbsolutePath(), System.currentTimeMillis() + "_" + data.getId() + ".png");
                        return false;
                    }
                }).preload();
    }

    private void loadImage(ImageView view, String path){
        Glide.with(context)
                .asBitmap()
                .load(path)
                .into(view);
    }

    class ViewHolder extends RecyclerView.ViewHolder {
        private ViewDataBinding binding;
        public ViewHolder(ViewDataBinding binding) {
            super(binding.getRoot());
            this.binding = binding;
        }
        public ViewDataBinding getBinding() {
            return binding;
        }
    }

    private OnListener listener;
    public void setListener(OnListener listener){
        this.listener = listener;
    }

    public interface OnListener{
        //        void setNextTime(int time);
        void save(File file, String saveName);
//        void showUrl(String url, int pos);
    }
}
